#include<stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
	int n;
	char string[52];
	struct node *next;
}Node;

#define CreateNode NewNode()
Node *NewNode();
int count_inver(char *str, int len);

void insert(Node *root,Node *p);
void printQueue(Node *root);

int main() 
{ 

#ifdef FILEIO
	freopen("in.txt","r",stdin); 
	freopen("out.txt","w",stdout); 
#endif

	int n,m;

	Node *root = CreateNode;

	while(scanf("%d %d",&n,&m)!=EOF)
	{
		while(m--) 
		{
			Node *p = CreateNode;
			scanf("%s",p -> string);
			p -> n =  count_inver(p -> string,strlen(p -> string));
			insert(root,p);
		}
		printQueue(root);
	}
	
#ifdef FILEIO
	fclose(stdin);
	fclose(stdout);
#endif  

	return 0; 
}

void printQueue(Node *root)
{
	Node *f = root -> next ;
	Node *freeNode;

	while(f!=NULL)
	{
		printf("%s\n",f -> string);
		freeNode=f;
		f=f->next;
		free(freeNode);
	}
	root->next=NULL;
}

void insert(Node *root,Node *p)
{
	Node *f;
	Node *prev;
	if(root -> next == NULL)  
	{
		root -> next = p;
		return;
	}
	prev = root;
	f = root -> next;

	for(;f != NULL;f = f -> next) 
	{
		if(p -> n < f -> n)  
		{
			p -> next = f; 
			prev -> next = p;
			return;
		}
		else if(p -> n == f -> n)   
		{
			p -> next = f->next;
			f -> next = p;
			return;
		}
		prev = f;
	}
	// the last one , so we have to insert at the end
	prev -> next = p; 
}

Node *NewNode()
{
	Node *p = (Node *)malloc(sizeof(Node));
	memset(p,0,sizeof(Node));
	return p;
}


int count_inver(char *str, int len)
{
	int i;  
	int cnt = 0;
	int a[4] = {0};
	for(i = len - 1; i >= 0; i--) {
		switch (str[i]) {
		case 'A':
			a[1]++; 
			a[2]++; 
			a[3]++; 
			break;  
		case 'C':
			a[2]++; 
			a[3]++; 
			cnt += a[1];
			break;  
		case 'G':
			a[3]++; 
			cnt += a[2];
			break;  
		case 'T':
			cnt += a[3];
		}
	}
	return cnt;
}
